﻿using Corina.Commands;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Windows.Input;
using System.Linq;
using System.Windows;
using System.Windows.Printing;
using Corina.Datamodel.DataObject;
using Corina.Common;
using Corina.Datamodel.Base;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.IO;
using Corina.Controls.Silverlight;
using System.Net;

namespace Corina.Lantern.Hub.Viewmodels
{
    public class DeviceMeasureViewmodel : ViewmodelBase
    {
        #region Customer Variable
        PrintDocument printDoc = new PrintDocument();
        private Image ImageViewer { get; set; }

        private Image PictureViewer { get; set; }

        WebClient GetImageClient = new WebClient();

        WebClient DownloadGuobiaoClient = new WebClient();

        WebClient PictureClient = new WebClient();

        SaveFileDialog savefileDialog = new SaveFileDialog() { Filter = "PDF文件(*.pdf)|*.pdf|所有文件(*.*)|*.*" }; 
        #endregion

        public DeviceMeasureViewmodel()
        {
            PictureClient.OpenReadCompleted += PictureOpenReadCompleted;
            GetImageClient.OpenReadCompleted += OpenGuobiaoImageCompleted;
            DownloadGuobiaoClient.OpenReadCompleted += DownloadGuobiaoCompleted;

            MeasureClient.GetAllMeasureItemsCompleted += GetAllMeasureItemsCompleted;
            DeviceClient.GetAllDeviceKindCompleted += GetAllDeviceKindCompleted;
            if (DataContext.IsValid)
            {
                LoadData();
                LoadRelatedData();
            }
        }

        

        #region Methods
        private void GetAllDeviceKindCompleted(object sender, DataService.GetAllDeviceKindCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                DeviceKindCollection = new ObservableCollection<DeviceKindInfo>(e.Result.Entities.OfType<DeviceKindInfo>());
            }
        }

        private void GetAllMeasureItemsCompleted(object sender, DataService.GetAllMeasureItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                //if(Environment.OSVersion.Platform == PlatformID.MacOSX)
                //{
                //    MessageBox.Show(string.Join("\r\n", e.Result.DataObjects));
                //}
                if (e.Result.Result == ResultValue.Succeed)
                {
                    var items = (from t in e.Result.DataObjects
                                 select new
                                 {
                                     ItemIndex = t["ROW_NUMBER"],
                                     Id = t["Id"],
                                     DeviceSn = (string)t["DeviceSn"],
                                     Kind = (string)t["Kind"],
                                     ProofValue = t["ProofValue"],
                                     Name = t["Name"],
                                     Density = (double)t["Density"],
                                     Temperature = (double)t["Temperature"],
                                     Humidity = (double)t["Humidity"],
                                     Tester = (string)t["Tester"],
                                     Specimen = t["Specimen"],
                                     TransType = (TransTypeValue)Convert.ToInt32(t["TransType"]),
                                     TestTime = Convert.ToDateTime(t["TestTime"]),
                                     MobileOrIP = t["MobileOrIP"],
                                     UserName = t["UserName"],
                                     Guobiao = t["Guobiao"],
                                     DocumentName = t["DocumentName"],
                                     PreviewImage = t["PreviewImage"],
                                     Picture = 1
                                 });
                    ItemsCollection = new ObservableCollection<object>(items);
                    ItemsCount = e.Result.TotalCount;
                    if (items.Count() > 0)
                    {
                        var EndTime = items.Select(t => t.TestTime).Max();
                        var StartTime = items.Select(t => t.TestTime).Min();

                        PrintTestTime = string.Format("{0} 至 {1}", StartTime.ToString("yyyy年MM月dd日"), EndTime.ToString("yyyy年MM月dd日"));
                    }
                    if (AddToPrintList)
                    {
                        var newlist = PrintItems.Concat(ItemsCollection);
                        PrintItems = new ObservableCollection<object>(newlist);
                    }
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message + "\r\n" + e.Error.InnerException.Message);
            }
            IsBusy = false;
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            List<QueryCondition> conditions = new List<QueryCondition>();
            conditions.Add(new QueryCondition("Density", DensityStart == null ? int.MinValue : DensityStart, DensityEnd == null ? int.MaxValue : DensityEnd));
            conditions.Add(new QueryCondition("Humidity", HumityStart == null ? int.MinValue : HumityStart, HumityEnd == null ? int.MaxValue : HumityEnd));
            conditions.Add(new QueryCondition("TestTime", TestTimeStart == null ? "2001-01-01" : TestTimeStart.Value.Date.ToString("yyyy-MM-dd"), TestTimeEnd == null ? DateTime.MaxValue.ToString("yyyy-MM-dd") : TestTimeEnd.Value.Date.AddDays(1).ToString("yyyy-MM-dd")));
            conditions.Add(new QueryCondition("Temperature", TemperatureStart == null ? int.MinValue : TemperatureStart, TemperatureEnd == null ? int.MaxValue : TemperatureEnd));

            string jsonString = JsonHelper.Stringify(conditions);

            //if (Environment.OSVersion.Platform == PlatformID.MacOSX)
            //{
            //    MessageBox.Show(string.Join("\r\n", Account, Password, DeviceSn, KindId, MeasureName, Tester, jsonString, Index));
            //}

            MeasureClient.GetAllMeasureItemsAsync(Account, Password, DeviceSn, KindId, 0, MeasureName, Tester, jsonString, Index, 20);
        }

        private void LoadRelatedData()
        {
            DeviceClient.GetAllDeviceKindAsync();
        }

        public void SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        { 
            
        }

        public void UILoaded(object sender, EventArgs e)
        {
            
            Page page = sender as Page;
            ImageViewer = (Image)page.FindName("imageViewer");
            PictureViewer = (Image)page.FindName("pictureViewer");
        }

        private void OpenGuobiaoImageCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.Result);
                ImageViewer.Source = image;
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
            LoadingImage = false;
        }

        private void DownloadGuobiaoCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            byte[] buffer = new byte[e.Result.Length];
            e.Result.Read(buffer, 0, (int)e.Result.Length);
            Stream stream = savefileDialog.OpenFile();
            stream.BeginWrite(buffer, 0, buffer.Length, OnSaveAsyncCallback, stream);
        }

        private void OnSaveAsyncCallback(IAsyncResult result)
        {
            Stream stream = (Stream)result.AsyncState;
            stream.EndWrite(result);
            stream.Close();
            MessageBox.Show("下载完成。");
        }
        #endregion

        #region Collection
        private ObservableCollection<DeviceKindInfo> _deviceKindCollection;
        public ObservableCollection<DeviceKindInfo> DeviceKindCollection
        {
            get { return _deviceKindCollection; }
            set
            {
                _deviceKindCollection = value;
                RaisePropertyChanged(() => DeviceKindCollection);
            }
        }

        private ObservableCollection<object> _itemsCollection;
        public ObservableCollection<object> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }
        #endregion

        #region Details
        private object _selectedMeasureItem;
        public object SelectedMeasureItem
        {
            get { return _selectedMeasureItem; }
            set
            {
                _selectedMeasureItem = value;
                RaisePropertyChanged(() => SelectedMeasureItem);
                RaisePropertyChanged(() => ShowItemDetail);
            }
        }

        public bool ShowItemDetail
        {
            get { return SelectedMeasureItem != null; }
        }
        #endregion

        #region Guobiao
        private bool _showGuobiaoDocument = false;
        public bool ShowGuobiaoDocument
        {
            get { return _showGuobiaoDocument; }
            set {
                _showGuobiaoDocument = value;
                RaisePropertyChanged(() => ShowGuobiaoDocument);
            }
        }

        private void GetDocument(string filename)
        {
            //try
            //{
            //    string url = string.Format("{0}LoadFile.aspx?f=Guobiao&n={1}", WebServiceAddress, "GB2012.pdf");
            //    Uri documentUri = new Uri(url);
            //    var myHttpPartRetriever = new HttpStreamingPartRetriever(documentUri);
            //    DocumentViewer.LoadAsync(myHttpPartRetriever, OnLoadAsyncCallback);
            //}
            //catch(Exception ex) {
            //    MessageBox.Show(ex.Message);
            //}
        }

        private void GetImage(string name)
        {
            LoadingImage = true;
            string url = string.Format("http://static.byshuju.cn/PreviewImage/{0}", name);
            Uri imageUri = new Uri(url);
            try
            {
                GetImageClient.CancelAsync();
                GetImageClient.OpenReadAsync(imageUri);
            }
            catch { }
        }

        public void OnLoadAsyncCallback(Exception ex)
        {
            if (ex != null)
            {
                //An error has occurred
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                MessageBox.Show("An error has occurred: " + ex.Message);
            }
           
        }

        private bool _loadingImage = false;
        public bool LoadingImage
        {
            get { return _loadingImage; }
            set {
                _loadingImage = value;
                RaisePropertyChanged(() => LoadingImage);
            }
        }

        private void DownloadGuobiaoFile(string documentName)
        {
            string url = string.Format("{0}LoadFile.aspx?f=Guobiao&n={1}", WebServiceAddress, documentName);
            Uri fileUrl = new Uri(url);
            DownloadGuobiaoClient.OpenReadAsync(fileUrl);
        }

        private string _guobiaoDocumentName = string.Empty;
        public string GuobiaoDocumentName
        {
            get { return _guobiaoDocumentName; }
            set {
                _guobiaoDocumentName = value;
                RaisePropertyChanged(() => GuobiaoDocumentName);
                RaisePropertyChanged(() => DownloadGuobiaoFileCommand);
            }
        }
        #endregion

        #region Search
        private string _tester = string.Empty;
        public string Tester
        {
            get { return _tester; }
            set
            {
                _tester = value;
                RaisePropertyChanged(() => Tester);
            }
        }

        private string _deviceSn = string.Empty;
        public string DeviceSn
        {
            get { return _deviceSn; }
            set
            {
                _deviceSn = value;
                RaisePropertyChanged(() => DeviceSn);
            }
        }

        private int _userId = 0;
        public int UserId
        {
            get { return _userId; }
            set
            {
                _userId = value;
                RaisePropertyChanged(() => UserId);
            }
        }

        private DeviceKindInfo _selectedDeviceKind;
        public DeviceKindInfo SelectedDeviceKind
        {
            get { return _selectedDeviceKind; }
            set
            {
                _selectedDeviceKind = value;
                RaisePropertyChanged(() => SelectedDeviceKind);
                KindId = SelectedDeviceKind == null ? 0 : SelectedDeviceKind.Id;
            }
        }

        private int _kindId = 0;
        public int KindId
        {
            get { return _kindId; }
            set
            {
                _kindId = value;
                RaisePropertyChanged(() => KindId);
            }
        }

        private string _measureName = string.Empty;
        public string MeasureName
        {
            get { return _measureName; }
            set
            {
                _measureName = value;
                RaisePropertyChanged(() => MeasureName);
            }
        }

        #region Density
        private double? _densityStart;
        public double? DensityStart
        {
            get { return _densityStart; }
            set
            {
                _densityStart = value;
                RaisePropertyChanged(() => DensityStart);
            }
        }

        private double? _densityEnd;
        public double? DensityEnd
        {
            get { return _densityEnd; }
            set
            {
                _densityEnd = value;
                RaisePropertyChanged(() => DensityEnd);
            }
        } 
        #endregion

        #region Humidity
        private double? _humidityStart;
        public double? HumityStart
        {
            get { return _humidityStart; }
            set
            {
                _humidityStart = value;
                RaisePropertyChanged(() => HumityStart);
            }
        }

        private double? _humidityEnd;
        public double? HumityEnd
        {
            get { return _humidityEnd; }
            set
            {
                _humidityEnd = value;
                RaisePropertyChanged(() => HumityEnd);
            }
        }
        #endregion

        #region Temperature
        private double? _temperatureStart;
        public double? TemperatureStart
        {
            get { return _temperatureStart; }
            set
            {
                _temperatureStart = value;
                RaisePropertyChanged(() => TemperatureStart);
            }
        }

        private double? _temperatureEnd;
        public double? TemperatureEnd
        {
            get { return _temperatureEnd; }
            set
            {
                _temperatureEnd = value;
                RaisePropertyChanged(() => TemperatureEnd);
            }
        }
        #endregion

        private DateTime? _testTimeStart;
        public DateTime? TestTimeStart
        {
            get { return _testTimeStart; }
            set
            {
                _testTimeStart = value;
                RaisePropertyChanged(() => TestTimeStart);
            }
        }

        private DateTime? _testTimeEnd = DateTime.Now;
        public DateTime? TestTimeEnd
        {
            get { return _testTimeEnd; }
            set
            {
                _testTimeEnd = value;
                RaisePropertyChanged(() => TestTimeEnd);
            }
        }
        #endregion

        #region Command
        public ICommand LoadCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Index = 1;
                        LoadData();
                    }
                };
            }
        }

        public ICommand ShowPrintCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        PrintItems = new ObservableCollection<object>(ItemsCollection);
                        ShowPrintView = true;
                    }
                };
            }
        }

        public ICommand HidePrintCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        ShowPrintView = false;
                        AddToPrintList = false;
                    }
                };
            }
        }

        public ICommand PrintCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    PrintUIElement = t as UIElement;

                    printDoc.PrintPage -= PrintPage;
                    printDoc.BeginPrint -= BeginPrint;
                    printDoc.EndPrint -= EndPrint;

                    printDoc.PrintPage += PrintPage;
                    printDoc.BeginPrint += BeginPrint;
                    printDoc.EndPrint += EndPrint;
                    printDoc.Print("Measure Report");
                });
            }
        }

        public ICommand SaveAsPoictureCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    WriteableBitmap bitmap = new WriteableBitmap(t as UIElement, null);
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter = "PNG Files (*.png)|*.png|All Files (*.*)|*.*";
                    dialog.DefaultExt = ".png";
                    dialog.FilterIndex = 1;

                    if ((bool)dialog.ShowDialog())
                    {
                        using (Stream fs = dialog.OpenFile())
                        {
                            int width = bitmap.PixelWidth;
                            int height = bitmap.PixelHeight;

                            EditableImage ei = new EditableImage(width, height);

                            for (int i = 0; i < height; i++)
                            {
                                for (int j = 0; j < width; j++)
                                {
                                    int pixel = bitmap.Pixels[(i * width) + j];
                                    ei.SetPixel(j, i,
                                                (byte)((pixel >> 16) & 0xFF),
                                                (byte)((pixel >> 8) & 0xFF),
                                                (byte)(pixel & 0xFF),
                                                (byte)((pixel >> 24) & 0xFF)
                                    );
                                }
                            }
                            //获取流
                            Stream png = ei.GetStream();
                            int len = (int)png.Length;
                            byte[] bytes = new byte[len];
                            png.Read(bytes, 0, len);
                            fs.Write(bytes, 0, len);
                            MessageBox.Show("图片保存成功！");
                        }
                    }
                });
            }
        }

        public ICommand RemovePrintItemCommand
        {
            get
            {
                return new DelegateCommand(t => {
                    var item = PrintItems.FirstOrDefault(i => GetObjectPropertyValue(i, "Id") == t);
                    PrintItems.Remove(item);
                });
            }
        }

        public ICommand OrderDESCCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrEmpty(SelectedSortOption.Key); },
                    ExecuteCallback = delegate { 
                        OrderItems();
                    }
                };
            }
        }

        public ICommand OrderASCCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrEmpty(SelectedSortOption.Key); },
                    ExecuteCallback = delegate { 
                        OrderItems(false);
                    }
                };
            }
        }

        public ICommand HideItemDetailCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        SelectedMeasureItem = null;
                    }
                };
            }
        }

        public ICommand ShowItemDetailCommand
        {
            get
            {
                return new DelegateCommand(t => {
                    SelectedMeasureItem = t;
                });
            }
        }

        public ICommand ShowGuobiaoDocumentCommand
        {
            get {
                return new DelegateCommand(t =>
                {
                    ShowGuobiaoDocument = true;
                    string imageName = (string)GetObjectPropertyValue(t, "PreviewImage");
                    GuobiaoDocumentName = (string)GetObjectPropertyValue(t, "DocumentName");
                    GetImage(imageName);
                });
            }
        }

        public ICommand HideGuobiaoDocumentCommand
        {
            get
            {
                return new GenericCommand() { ExecuteCallback = delegate {
                    ShowGuobiaoDocument = false;
                    ImageViewer.Source = null;
                } };
            }
        }

        public ICommand DownloadGuobiaoFileCommand
        {
            get {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrEmpty(GuobiaoDocumentName); },
                    ExecuteCallback = delegate
                    {
                        if (savefileDialog.ShowDialog() == true)
                        {
                            DownloadGuobiaoFile(GuobiaoDocumentName);
                        }
                    }
                };
            }
        }

        #endregion

        #region Print
        private bool _addToPrintList = false;
        public bool AddToPrintList
        {
            get { return _addToPrintList; }
            set
            {
                _addToPrintList = value;
                RaisePropertyChanged(() => AddToPrintList);
            }
        }

        private string _printTestTime;
        public string PrintTestTime
        {
            get { return _printTestTime; }
            set
            {
                _printTestTime = value;
                RaisePropertyChanged(() => PrintTestTime);
            }
        }

        private bool _showPrintView = false;
        public bool ShowPrintView
        {
            get { return _showPrintView; }
            set
            {
                _showPrintView = value;
                RaisePropertyChanged(() => ShowPrintView);
            }
        }

        private bool _showPrintOption = false;
        public bool ShowPrintOption
        {
            get { return _showPrintOption; }
            set
            {
                _showPrintOption = value;
                RaisePropertyChanged(() => ShowPrintOption);
            }
        }

        private bool _printing = false;
        public bool Printing
        {
            get { return _printing; }
            set
            {
                _printing = value;
                RaisePropertyChanged(() => Printing);
            }
        }

        public string CertNumber
        {
            get
            {
                Random ran = new Random();
                return DateTime.Now.ToString("yyyyMMddHHmm") + ran.Next(0, 100).ToString().PadLeft(2, '0');
            }
        }

        public DateTime CertAllocateDate
        {
            get
            {
                return DateTime.Now;
            }
        }

        public string ReportName
        {
            get
            {
                if(IsDesignMode)
                {
                    return "昆明市西山区工商局";
                }
                return DataContext.CurrentAccount.Name;
            }
        }

        private void OrderItems(bool down = true)
        {
            List<object> items = new List<object>();
            for (var i = 0; i < PrintItems.Count; i++)
            {
                var item = PrintItems[i];
                if (items.Count == 0)
                {
                    items.Insert(0, item);
                }
                else if (items.Count == 1)
                {
                    IComparable objValue = (IComparable)GetObjectPropertyValue(items[0], SelectedSortOption.Key);
                    IComparable itemValue = (IComparable)GetObjectPropertyValue(item, SelectedSortOption.Key);
                    if (objValue.CompareTo(itemValue) > 0)
                    {
                        items.Insert(1, item);
                    }
                    else{
                        items.Insert(0, item);
                    }
                }
                else
                {
                    for (var j = 0; j < items.Count; )
                    {
                        IComparable obj1Value = (IComparable)GetObjectPropertyValue(items[j], SelectedSortOption.Key);
                        IComparable itemValue = (IComparable)GetObjectPropertyValue(item, SelectedSortOption.Key);

                        if (j < items.Count - 1)
                        {
                            
                            IComparable obj2Value = (IComparable)GetObjectPropertyValue(items[j + 1], SelectedSortOption.Key);

                            if (obj1Value.CompareTo(itemValue) <= 0)
                            {
                                items.Insert(j, item);
                                break;
                            }
                            else if (obj1Value.CompareTo(itemValue) > 0 && obj2Value.CompareTo(itemValue) <= 0)
                            {
                                items.Insert(j + 1, item);
                                break;
                            }
                            else if (obj2Value.CompareTo(itemValue) > 0 && j < items.Count - 1)
                            {
                                j++;
                            }
                            
                        }
                        else
                        {
                            if (obj1Value.CompareTo(itemValue) > 0)
                            {
                                items.Add(item);
                                break;
                            }
                            
                        }
                    }
                }
            }

            items.ForEach(t => {
                Console.WriteLine(GetObjectPropertyValue(t, "Density"));
            });


            PrintItems = new ObservableCollection<object>(items);
            RaisePropertyChanged(() => PrintItems);
        }

        private KeyValuePair<string, string> _selectedSortOption;
        public KeyValuePair<string,string> SelectedSortOption
        {
            get { return _selectedSortOption; }
            set
            {
                _selectedSortOption = value;
                RaisePropertyChanged(() => SelectedSortOption);
                RaisePropertyChanged(() => OrderASCCommand);
                RaisePropertyChanged(() => OrderDESCCommand);
            }
        }
        public IEnumerable<KeyValuePair<string, string>> OrderCondition
        {
            get
            {
                yield return new KeyValuePair<string, string>("Id", "编号");
                yield return new KeyValuePair<string, string>("Humidity", "湿度");
                yield return new KeyValuePair<string, string>("Density", "浓度");
                yield return new KeyValuePair<string, string>("Temperature", "温度");
                yield return new KeyValuePair<string, string>("TestTime", "时间");
                yield return new KeyValuePair<string, string>("Name", "检测项目");
            }
        }

        private ObservableCollection<object> _printItems;
        public ObservableCollection<object> PrintItems
        {
            get { return _printItems; }
            set
            {
                _printItems = value;
                RaisePropertyChanged(() => PrintItems);
                RaisePropertyChanged(() => MeasureProject);
                RaisePropertyChanged(() => MeasureSpecimen);

            }
        }

        public IEnumerable<string> MeasureProject
        {
            get
            {
                if(PrintItems == null)
                {
                    return null;
                }
                List<string> list = new List<string>();
                PrintItems.ForEach(t =>
                {
                    string name = (string)GetObjectPropertyValue(t, "Name");
                    if (!list.Contains(name))
                    {
                        list.Add(name);
                    }
                });
                return list;
            }
        }

        public IEnumerable<string> MeasureSpecimen
        {
            get
            {
                if (PrintItems == null)
                {
                    return null;
                }
                List<string> list = new List<string>();
                PrintItems.ForEach(t =>
                {
                    string name = (string)GetObjectPropertyValue(t, "Specimen");
                    if (!list.Contains(name))
                    {
                        list.Add(name);
                    }
                });
                return list;
            }
        }

        private UIElement _printUIElement;
        public UIElement PrintUIElement
        {
            get { return _printUIElement; }
            set
            {
                _printUIElement = value;
                RaisePropertyChanged(() => PrintUIElement);
            }
        }

        public void LoadMoreItems(object sender,RoutedEventArgs e)
        {
            AddToPrintList = true;
        }

        private void EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            Printing = false;
            PrintUIElement = null;

        }

        private void BeginPrint(object sender, BeginPrintEventArgs e)
        {
            Printing = true;
        }

        private void PrintPage(object sender, PrintPageEventArgs e)
        {
            Size pageSize = e.PrintableArea;

            int count = (int)(PrintUIElement.RenderSize.Height + (pageSize.Height - 1)) / (int)pageSize.Height;



            Console.WriteLine(count);

            if (count < 2)
            {
                e.PageVisual = PrintUIElement;
            }
            else
            {
                e.PageVisual = PrintUIElement;
                //var printUI = PrintUIElement.Measure()
            }
        }

        private string _printingContent = "正在打印报告，请稍后...";
        public string PrintingContent
        {
            get { return _printingContent; }
            set
            {
                _printingContent = value;
                RaisePropertyChanged(() => PrintingContent);
            }
        }
        #endregion

        #region Move Panel
        Point cusPoint;
        bool isMouseMove = false;

        public void CompletedMove(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement element = sender as FrameworkElement;
            isMouseMove = false;
            element.ReleaseMouseCapture();
            cusPoint.X = 0;
            cusPoint.Y = 0;
        }

        public void MoveElememt(object sender, MouseEventArgs e)
        {
            FrameworkElement element = sender as FrameworkElement;
            if (isMouseMove)
            {
                double curX = e.GetPosition(null).X - cusPoint.X;
                double curY = e.GetPosition(null).Y - cusPoint.Y;
                element.SetValue(Canvas.TopProperty, curY + (double)element.GetValue(Canvas.TopProperty));
                element.SetValue(Canvas.LeftProperty, curX + (double)element.GetValue(Canvas.LeftProperty));

                cusPoint = e.GetPosition(null);
            }
        }

        public void ReadyToMove(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement element = sender as FrameworkElement;
            cusPoint = e.GetPosition(null);
            isMouseMove = true;
            if (null != element)
            {
                element.CaptureMouse();
            }
        }
        #endregion

        #region PictureFrame
        private bool _showPictureFrame=false;
        public bool ShowPictureFrame
        {
            get { return _showPictureFrame; }
            set
            {
                _showPictureFrame = value;
                RaisePropertyChanged(() => ShowPictureFrame);
                if(ShowPictureFrame)
                {
                    RaisePropertyChanged(() => PictureThumbnailCollection);
                    SelectedPicture = PictureThumbnailCollection.FirstOrDefault();
                }
                GC.Collect();
            }
        }

        private bool _loaddingPicture = false;
        public bool LoadingPicture
        {
            get { return _loaddingPicture; }
            set
            {
                _loaddingPicture = value;
                RaisePropertyChanged(() => LoadingPicture);
            }
        }

        public ICommand ShowPictureFrameCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        ShowPictureFrame = !ShowPictureFrame;
                    }
                };
            }
        }

        private object _selectedPicture;
        public object SelectedPicture
        {
            get { return _selectedPicture; }
            set{
                _selectedPicture = value;
                RaisePropertyChanged(() => SelectedPicture);
                if (SelectedPicture != null)
                {
                    LoadPicture(GetObjectPropertyValue(SelectedPicture, "Name") as string);
                }
            }
        }

        private void LoadPicture(string name)
        {
            LoadingPicture = true;
            string url = string.Format("http://static.byshuju.cn/MeasurePictures/{0}?g={1}", name, System.Guid.NewGuid());
            //string url = string.Format("{2}loadfile.aspx?f=MeasurePictures&n={0}&g={1}", name, System.Guid.NewGuid(), WebServiceAddress);
            //MessageBox.Show(url);
            try
            {
                PictureClient.CancelAsync();
                PictureClient.OpenReadAsync(new Uri(url));
            }
            catch { }
        }

        private void PictureOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.Result);
                PictureViewer.Source = image;
            }
            else
            {
                //MessageBox.Show(e.Error.Message);
            }
            LoadingPicture = false;
            GC.Collect();
        }

        public IEnumerable<object> PictureThumbnailCollection
        {
            get
            {
                for (var i = 1; i < 5; i++)
                {
                    yield return new { Name = i + ".jpg", Id = System.Guid.NewGuid() }; 
                }
            }
        }
        #endregion
    }
}
